package com.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.to.es.SkuEsModel;
import com.common.utils.R;
import com.gulimall.search.config.GuilimallElasticSearchConfig;
import com.gulimall.search.constant.EsConstant;
import com.gulimall.search.feign.ProductFeignService;
import com.gulimall.search.service.MallSearchService;
import com.gulimall.search.vo.AttrResponseVo;
import com.gulimall.search.vo.BrandVo;
import com.gulimall.search.vo.SearchParam;
import com.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.plugins.NetworkPlugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {


    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     *
     * @param searchParam 检索参数
     */
    @Override
    public SearchResult search(SearchParam searchParam)  {
        //开始检索
        SearchResult result = null;
        //1、构建出查询需要的sql语句
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            SearchResponse search =  client.search(searchRequest, GuilimallElasticSearchConfig.COMMON_OPTIONS);
            //分析检索结果
            result = buildSearchResult(search,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 构建结果数据
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {
        SearchHits hits = response.getHits();
        Aggregations aggregations = response.getAggregations();
        SearchResult result = new SearchResult();
        //1、返回所有查询到的商品
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String s = skuTitle.getFragments()[0].toString();
                    sku.setSkuTitle(s);
                }
                skuEsModels.add(sku);
            }
        }
        result.setProducts(skuEsModels);
        //2、当前所有商品涉及到的所有属性信息
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ArrayList< SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue(); //属性id
            attrVo.setAttrId(attrId);
            //属性名字
            String attr_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name_agg);
            //属性值
            List<String> arrayValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                return ((Terms.Bucket) item).getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(arrayValues);


            attrs.add(attrVo);
        }
        result.setAttrs(attrs);
        //3、当前商品所涉及的品牌信息
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        List<? extends Terms.Bucket> bucketsBrands = brand_agg.getBuckets();
        for (Terms.Bucket bucketsBrand : bucketsBrands) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String keyAsString = bucketsBrand.getKeyAsString(); //品牌id
            brandVo.setBrandId(Long.parseLong(keyAsString));
            //品牌默认图片
            ParsedStringTerms brand_img_agg = bucketsBrand.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            //品牌名字
            ParsedStringTerms brand_name_agg = bucketsBrand.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4、当前商品所涉及的分类的信息
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();//分类id
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //得到分类名
            ParsedStringTerms catalog_name_age = bucket.getAggregations().get("catalog_name_age");
            String catalogNAme = catalog_name_age.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogNAme);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //5、当前分页信息
        //5.1总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5.2总页码
        int totalPages = (int)total%EsConstant.PRODUCT_PAGESIZE == 0
                ?(int)total/EsConstant.PRODUCT_PAGESIZE : (int)(total/EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotaPages(totalPages);
        //5.3当前页码
        result.setPageNum(param.getPageNum());
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            arrayList.add(i);
        }
        result.setPageNavs(arrayList);

        //6、构建面包屑导航功能
        //6.1属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo attrResponseVo = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attrResponseVo.getAttrName());
                } else {
                    navVo.setNavValue(s[0]);
                }
                //将这个面包屑取消后，要跳到那个地方，将当前请求的地址的当前条件制空
                String replace = replaceQueryString(param, attr,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        //6.2品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            R r = productFeignService.BrandInfos(param.getBrandId());
            if (r.getCode() == 0){
                List<BrandVo> brandVoList = r.getData(new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = null;
                for (BrandVo brandVo : brandVoList) {
                    buffer.append(brandVo.getName()+";");
                    replace = replaceQueryString(param,brandVo.getBrandId()+"", "brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
            }
            navs.add(navVo);
            result.setNavs(navs);
        }
        //6.3分类
        return result;
    }

    private String replaceQueryString(SearchParam param, String attr,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "UTF-8");
            encode = encode.replace("+","%20"); //浏览器对空格编码和java不一样
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replace = param.get_queryString().replace("&"+key+"=" + encode, "");
        return replace;
    }

    /**
     * 准备检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构建检索请求
        /*
         * 模糊匹配
         */
        //1、构建bool -query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1、1 must的模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1、2 bool -filter 按照三级分类id查询
        if (param.getCatalog3Id() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //1.2 bool -filter 按照品牌的id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //1.2 bool -filter 按照所有指定属性来查询
        if (!StringUtils.isEmpty(param.getAttrs()) && param.getAttrs().size() > 0){
            //attrs=1_1.5寸:1.2寸&attrs=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attr检索条件 一个一个的来添加
                String[] s = attrStr.split("_");
                String  attrId = s[0];  //属性id
                String[] attrValue = s[1].split(":"); //属性检索的值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                //每一个都得生成一个
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //1.2 bool -filter 按照是否有库存来查询
        if (param.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() == 1));
        }
        //1.2 bool -filter 按照价格区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (!StringUtils.isEmpty(s[0]) &&  !StringUtils.isEmpty(s[1])){
                //区间
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (StringUtils.isEmpty(s[0]) ||  StringUtils.isEmpty(s[1])){
                if (param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[1]);
                }
                if (param.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);

        }
        sourceBuilder.query(boolQuery);

        //2.1 排序
        if (!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            //sort=hotScore_asc/desc
            String[] s = sort.split("_");
            sourceBuilder.sort(s[0],s[1].equals("asc")? SortOrder.ASC:SortOrder.DESC);
        }
        //2.2分页
        if (param.getPageNum()!=null) {
            sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        }
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            //有才有必要高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red' >");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /*
         * 聚合分析
         * 1、品牌聚合
         */
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //2、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_age").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        String s = sourceBuilder.toString();
        System.out.println("构建的DSL");
        System.out.println(s);
        return  new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
    }
























}
